import { defineStore } from 'pinia';
import { useGlobalType } from '../type/index.d';
import { nameEnum } from '../type/namEnum.d';
import { getDictionaryTableList } from '@/api/applicationManagement';
import { DictEnum } from '@/enums/commonEnum';
import { store } from '../store';
import { getProjectManagementPage } from '@/api/projectManagement';
export const useGlobal = defineStore(nameEnum.GLOBAL, {
  state: (): useGlobalType => {
    return {
      collapsed: false,
      dictionaryTable: <CommonTypes.DictionaryTableResult[]>[],
      currentProject: {},
      projectList: [],
    };
  },

  getters: {
    getCurrentProject(): any {
      return this.currentProject;
    },
    getProjectList(): any {
      return this.projectList;
    },
  },

  actions: {
    setMenuCollapsed(collapsed: boolean) {
      this.collapsed = collapsed;
    },

    setDictionaryTable(list: CommonTypes.DictionaryTableResult[]) {
      this.dictionaryTable = list;
    },

    async fetchDictionaryTable() {
      const data: CommonTypes.DictionaryTableResult[] = await getDictionaryTableList();
      this.setDictionaryTable(data);
    },

    getDictionaryTable(type: string): CommonTypes.DictionaryTableResult[] {
      const list = this.dictionaryTable
        .filter((item) => item.dictType === type)
        ?.map((item: any) => {
          if (type == DictEnum.componentData) {
            return {
              ...item,
              label: item.dictName,
              value: Number(item.dictValue),
            };
          }
          return {
            ...item,
            label: item.dictName,
            value: item.dictValue,
          };
        });
      return list ?? [];
    },
    setCurrentProject(data: any) {
      this.currentProject = data;
    },
    async fetchProject() {
      const data = await getProjectManagementPage({ currentPage: 1, pageSize: 9999, condition: {} });
      this.currentProject = data.records ? data.records[0] : {};
      this.projectList = data.records ?? [];
    },
  },
  persist: {
    enabled: true,
  },
});

// Need to be used outside the setup
export function useGlobalStoreWithOut() {
  return useGlobal(store);
}
